package cn.edu.qlnu.xky.test.task;

/**
 * @author wuweihong
 * @version 1.0
 * @date 2025/6/22 0:12
 * @Description: Please write your descriptions for this class.
 **/


import cn.edu.qlnu.xky.test.dao.BorrowDao;
import cn.edu.qlnu.xky.test.model.Borrow;
import cn.edu.qlnu.xky.test.utils.DateUtils;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class OverdueCheckTask {

    private BorrowDao borrowDao = new BorrowDao();

    public void startChecking() {
        System.out.println("开始启动定时任务，每小时轮询读者借阅是否超期，超期按每一天一角增加罚款..");
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 每天执行一次检查任务
        scheduler.scheduleAtFixedRate(this::checkAndMarkOverdue, 0, 1, TimeUnit.HOURS);
    }

    private void checkAndMarkOverdue() {
        List<Borrow> borrows = borrowDao.getUnreturnedBorrows();
        LocalDate currentDate = LocalDate.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (Borrow borrow : borrows) {
            try {
                LocalDate dueDate = borrow.getDueDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                boolean isOverdue = currentDate.isAfter(dueDate);

                if (isOverdue) {
                    borrow.setIsExceed(1);
                    borrow.setFine(DateUtils.getDayDifference(new Date(), borrow.getDueDate()));
                    borrowDao.updateBorrow(borrow);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
